//
//  SEGActivityRootViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/11.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGActivityRootViewController.h"
#import "SEGActivityListViewController.h"

@interface SEGActivityRootViewController () <UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView* titleScrollView;
@property (nonatomic, strong) UIButton* selectedBtn;
@property (nonatomic, strong) NSMutableArray<UIButton*>* titleBtnArray;

@property (nonatomic, assign) CGFloat UIScreenMargin;

@property (nonatomic, assign) CGFloat titleScrollViewWidth;

@property (nonatomic, assign) NSInteger titleScrollViewBtnWidth;
@property (nonatomic, strong) UIView* line;
@property (nonatomic, strong) UIScrollView* contentScrollView;
@property (nonatomic, assign) NSInteger titleScrollViewBtnCount;
@property (nonatomic, strong) NSArray* dataSource;

@end

@implementation SEGActivityRootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self showCustomNavigationRightButtonWithTitle:@"我参加的" image:nil hightlightImage:nil color:kColor_1];
 
    self.dataSource = @[@"活动广场"];
    self.title = self.aTitle.length > 0 ? self.aTitle : @"活动广场";
    
    for (NSString* str in self.dataSource) {
        BOOL isRecommand = [str isEqualToString:@"推荐"];
        SEGActivityListViewController* VC1 = [[SEGActivityListViewController alloc] initWithIsRecommand:isRecommand isMine:NO];
        [self addChildViewController:VC1];
    }
    [self setAllPrepareAtIndex:0];
    
    WeakSelf;
    //收到活动抽奖推送
    [[NSNotificationCenter defaultCenter] addObserverForName:SEGActivityLotteryNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf seg_checkActivityLotteryBubble];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self seg_checkActivityLotteryBubble];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 触发浏览行为
    [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.browse module:SEGIntegralModule.activitySquare businessID:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
    }];
    
    // 处理导航栈数据，如果存在之前的活动列表 需要删除掉
    NSMutableArray<UIViewController *> *tempArrays = [NSMutableArray array];
    [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[SEGActivityRootViewController class]]) {
            *stop = YES;
            return;
        }
        [tempArrays addObject:obj];
    }];
    [tempArrays addObject:self];
    self.navigationController.viewControllers = tempArrays;
}

/// 判断是否显示活动抽奖气泡
- (void)seg_checkActivityLotteryBubble {
    [[SEGUhomeMediator sharedInstance] seg_checkActivityLotteryBubble:@{@"vc" : self}];
}

//右侧按钮
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    //我参加的
    SEGActivityListViewController* VC1 = [[SEGActivityListViewController alloc] initWithIsRecommand:NO isMine:YES];
    VC1.title = @"我参加的";
    [self.navigationController pushViewController:VC1 animated:YES];
}


#pragma mark - 设置标题scrollView
- (void)setTitleScrollView
{
    return;
}
- (NSMutableArray<UIButton*>*)titleBtnArray
{
    if (!_titleBtnArray) {
        self.titleBtnArray = [[NSMutableArray alloc] init];
    }
    return _titleBtnArray;
}

- (void)setAllPrepareAtIndex:(NSInteger)index
{
    self.UIScreenMargin = LYScreenWidth() / 8; //设置间距
    
    self.titleScrollViewBtnWidth = 80;
    
    self.titleScrollViewBtnCount = self.dataSource.count;
    
    if (!self.titleScrollViewBtnCount || self.titleScrollViewBtnCount <= 0) {
        return;
    }
    
    if (self.titleScrollViewBtnCount * self.titleScrollViewBtnWidth >= (LYScreenWidth() - self.UIScreenMargin * 2)) {
        self.titleScrollViewWidth = LYScreenWidth() - self.UIScreenMargin * 2;
    }
    else {
        self.titleScrollViewWidth = self.titleScrollViewBtnCount * self.titleScrollViewBtnWidth;
    }
    
    [self setTitleScrollView];
    [self setContentScrollView];
    [self setTitleScrollViewBtn];
    [self titleViewBtnClick:self.titleBtnArray[index]];
}

- (void)setTitleScrollViewBtn
{
    
    [self.titleBtnArray removeAllObjects];
    
    for (int i = 0; i < self.dataSource.count; i++) {
        
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.tag = i;
        
        [self.titleBtnArray addObject:btn];
        
        CGFloat X = self.titleScrollViewBtnWidth * i;
        
        btn.frame = CGRectMake(X, 0, self.titleScrollViewBtnWidth, 44);
        
        if (btn.tag == 0) {
            self.selectedBtn = btn;
            [btn setTitleColor:kColor_T forState:UIControlStateNormal];
        }
        else {
            [btn setTitleColor:kColor_3 forState:UIControlStateNormal];
        }
        
        [btn setTitle:self.dataSource[i] forState:UIControlStateNormal];
        
        [btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        
        [btn addTarget:self action:@selector(titleViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.titleScrollView addSubview:btn];
    }
    
    if (self.titleBtnArray.count > 1) {
        [self.titleScrollView addSubview:self.line];
    }
}

#pragma mark - 监听标题按钮点击
- (void)titleViewBtnClick:(UIButton*)btn
{
    
    // 1.标题状态改变
    self.selectedBtn.selected = NO;
    [self.selectedBtn setTitleColor:kColor_3 forState:UIControlStateNormal];
    btn.selected = YES;
    self.selectedBtn = btn;
    [self.selectedBtn setTitleColor:kColor_T forState:UIControlStateNormal];
    
    // 1.标题状态改变
    self.selectedBtn.selected = NO;
    btn.selected = YES;
    self.selectedBtn = btn;
    [self.contentScrollView setContentOffset:CGPointMake(LYScreenWidth() * btn.tag, 0) animated:YES] ;
    
    NSInteger item = btn.tag;
    
    CGFloat offSetX = 0;
    if (btn.center.x < LYScreenWidth() / 2) {
        offSetX = 0;
    }
    else if ((self.titleScrollView.contentSize.width - btn.center.x) < LYScreenWidth() / 2) {
        offSetX = self.titleScrollView.contentSize.width - LYScreenWidth();
    }
    else {
        offSetX = btn.center.x - LYScreenWidth() / 2;
    }
    
    [self.titleScrollView setContentOffset:CGPointMake(offSetX, 0) animated:YES];
    
    // 2.显示目标View
    [self showTargetViewWithIndex:btn.tag];
    
    if (self.titleBtnArray.count > 1) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.line.frame = CGRectMake(item * self.titleScrollViewBtnWidth + 10, 42, self.titleScrollViewBtnWidth - 20, 2);
            
        }];
    }
}

- (UIView*)line
{
    if (!_line) {
        _line = [[UIView alloc] init];
        _line.backgroundColor = kColor_T;
    }
    return _line;
}
- (void)scrollViewWillEndDragging:(UIScrollView*)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint*)targetContentOffset
{
    CGPoint p = *targetContentOffset;
    NSInteger d = p.x / LYScreenWidth();
    UIButton* btn = self.titleBtnArray[d];
    
    [self titleViewBtnClick:btn];
}

#pragma mark - 设置contentScrollView
- (void)setContentScrollView
{
//    self.automaticallyAdjustsScrollViewInsets = NO;
    UIScrollView* contentScrollView = [[UIScrollView alloc] init];
    contentScrollView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
    contentScrollView.backgroundColor = kColor_W;
    
    CGFloat contentW = self.childViewControllers.count * LYScreenWidth();
    contentScrollView.contentSize = CGSizeMake(contentW, 0);
    contentScrollView.showsHorizontalScrollIndicator = NO;
    contentScrollView.showsVerticalScrollIndicator = NO;
    contentScrollView.pagingEnabled = YES;
    contentScrollView.scrollsToTop = NO;
    contentScrollView.delegate = self;
    [self.view addSubview:contentScrollView];
    
    self.contentScrollView = contentScrollView;
}

- (void)showTargetViewWithIndex:(NSInteger)index
{
    UIViewController* tableVC = (UIViewController*)self.childViewControllers[index];
    
    // 如果已经添加了View,不做重复操作
    if (!tableVC.view.window) {
        [self.contentScrollView addSubview:tableVC.view];
        tableVC.view.frame = CGRectMake(LYScreenWidth() * index, 0, LYScreenWidth(), self.contentScrollView.bounds.size.height);
        //tableVC.view.contentInset = UIEdgeInsetsMake(YJNavBarMaxY + self.scrollTitleHeight, 0, YJTabBarH, 0);
    }
    
    tableVC.view.frame = CGRectMake(0, 0, LYScreenWidth(), self.contentScrollView.bounds.size.height);
}

@end
